<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { updatePool } from '#/api/gis/valve';
import type { EditPoolParams } from '#/api/gis/valve';
import { message } from 'ant-design-vue';
import { ref, nextTick } from 'vue';
import { z } from '#/adapter/form';



const data = ref();

const [EditModal, EditmodalApi] = useVbenModal({
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      data.value = EditmodalApi.getData<Record<string, any>>();
      // 确保 BaseForm 渲染完成后再设置初始值
      nextTick(() => {
        setTimeout(() => {
          if (data.value) {
            const plainData = JSON.parse(JSON.stringify(data.value));
            // console.log('plainData:', plainData);

            // 处理 plainData.data 中的值以满足表单要求
            //1,经纬度
            if (plainData.data && plainData.data.location) {
              const locationParts = plainData.data.location.split(', ');
              if (locationParts.length === 2) {
                const longitude = locationParts[0].split(': ')[1];
                const latitude = locationParts[1].split(': ')[1];
                plainData.data.longitude = longitude;
                plainData.data.latitude = latitude;
              }
            }
            //2,状态
            // 2. 处理状态
            if (plainData.data.valveType) {
                plainData.data.valveType = plainData.data.valveType === '正常' ? 1 : 0;
            }
            //1.处理备注
            if(plainData.data.remark ==="---"){
              plainData.data.remark = "";
            }

            //设置 BaseForm 的初始值
            BaseFormApi.setValues(plainData.data,false);
            BaseFormApi.getValues().then((values) => {
            console.log(' 获取到的值:', values);
            });

          }
        }, 100); // 延迟 100ms
      });
    };
  }
});

const [BaseForm, BaseFormApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入阀池编号',
        disabled: true,
      },
      fieldName: 'poolCode',
      label: '阀池编号',
      rules:"required",
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入阀池名称',
      },
      fieldName: 'poolName',
      label: '阀池名称',
      rules:"required",
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入关联管线编号',
      },
      fieldName: 'pipelineCode',
      label: '关联管线编号',
      rules:"required",
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
        {
            label: '蝶型',
            value: 2,
          },
          {
            label: '球型',
            value: 1,
          },
          {
            label: '闸型',
            value: 0,
          },
        ],
        placeholder: '请选择阀池类型',
      },
      fieldName: 'valveType',
      label: '阀池类型',
      rules:"selectRequired",
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入经度',
      },
      fieldName: 'longitude',
      label: '经度',
      rules: z.string()
        .min(1, { message: '请输入经度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -180 && numValue <= 180;
        }, {
          message: '经度必须在 -180 到 180 之间',
        }),
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入纬度',
      },
      fieldName: 'latitude',
      label: '纬度',
      rules: z.string()
        .min(1, { message: '请输入纬度' })
        .refine((value) => {
          const numValue = parseFloat(value);
          return !isNaN(numValue) && numValue >= -90 && numValue <= 90;
        }, {
          message: '纬度必须在 -90 到 90 之间',
        }),
    },
    
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入备注',
      },
      fieldName: 'remark',
      label: '备注',
    },
  ],
});

// 定义一个自定义事件，用于在修改完数据后刷新页面
const emit = defineEmits(['refreshTable']);
function onSubmit(values: Record<string, any>) {
  const params = values as EditPoolParams;
  params.location = `POINT(${params.longitude} ${params.latitude})`;
  updatePool(params).then(() => {
    EditmodalApi.close();
    message.success('修改阀池成功');
  }).catch((error) => {
    console.error('修改阀池失败:', error);
  });
  emit('refreshTable'); // 触发自定义事件
}
</script>

<template>
  <EditModal title="修改阀池">
    <BaseForm />
    <template #prepend-footer>
    </template>
  </EditModal>
</template>
